package org.misty.seckill.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class LuaScript implements InitializingBean {
  public static final String SAMPLE = "redisScripts/sample.lua";
  public static final String PUT_ON_SALE = "redisScripts/putOnSale.lua";
  public static final String PLACE_ORDER = "redisScripts/placeOrder.lua";


  private static final Logger LOGGER = LoggerFactory.getLogger(LuaScript.class);
  private static final ConcurrentHashMap<String, String> CACHE = new ConcurrentHashMap<>();

  @Autowired
  private RedisService redisService;

  @Override
  public void afterPropertiesSet() {
    load(SAMPLE);
    load(PUT_ON_SALE);
    load(PLACE_ORDER);
  }

  public String sample() {
    return CACHE.get(SAMPLE);
  }

  public String putOnSale() {
    return CACHE.get(PUT_ON_SALE);
  }

  public String placeOrder() {
    return CACHE.get(PLACE_ORDER);
  }

  private void load(String path) {
    try {
      var script = Files.readString(Paths.get(ClassLoader.getSystemResource(path).toURI()), StandardCharsets.UTF_8);
      var sha = redisService.scriptLoad(script);
      CACHE.put(path, sha);
    } catch (Exception e) {
      LOGGER.error("加载LUA失败", e);
    }
  }
}
